using System;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;

namespace muduoDotNet.Tests
{
    public class SimpleEventLoopTest
    {
        private readonly ITestOutputHelper _output;

        public SimpleEventLoopTest(ITestOutputHelper output)
        {
            _output = output;
        }

        [Fact]
        public void TestSimpleEventLoopExecution()
        {
            _output.WriteLine("TestSimpleEventLoopExecution started");
            var loop = new EventLoop();
            int taskExecuted = 0;
            var taskCompletedEvent = new ManualResetEventSlim(false);

            // 启动事件循环
            var loopTask = Task.Run(() => 
            {
                try
                {
                    loop.Start();
                }
                catch (Exception ex)
                {
                    _output.WriteLine($"Loop exception: {ex}");
                    throw;
                }
            });

            // 等待事件循环启动
            Thread.Sleep(50);

            // 添加简单任务
            loop.QueueInLoop(() =>
            {
                _output.WriteLine("Simple task executing");
                Interlocked.Exchange(ref taskExecuted, 1);
                taskCompletedEvent.Set();
                loop.Stop();
            });

            // 等待任务完成
            bool completed = taskCompletedEvent.Wait(2000);
            bool loopCompleted = loopTask.Wait(1000);
            
            Assert.True(completed, "Task should complete");
            Assert.True(loopCompleted, "Loop should complete");
            Assert.Equal(1, taskExecuted);
            
            loop.Dispose();
            _output.WriteLine("TestSimpleEventLoopExecution completed");
        }
    }
}